package com.shiwaixiangcun.monitor.service.impl;

import com.rabbit.spring.data.search.SearchOperator;
import com.rabbit.spring.data.search.Searchable;
import com.rabbit.spring.data.search.filter.SearchFilter;
import com.rabbit.spring.data.search.filter.SearchFilterHelper;
import com.shiwaixiangcun.core.exceptions.MonkeyException;
import com.shiwaixiangcun.core.plugin.dto.MonkeyDto;
import com.shiwaixiangcun.core.service.BaseServiceImpl;
import com.shiwaixiangcun.core.utils.MonkeyUtils;
import com.shiwaixiangcun.monitor.domain.User;
import com.shiwaixiangcun.monitor.domain.WorkOrder;
import com.shiwaixiangcun.monitor.domain.WorkOrderQualityRecord;
import com.shiwaixiangcun.monitor.dto.WorkOrderDetailDto;
import com.shiwaixiangcun.monitor.dto.WorkOrderQualityRecordDto;
import com.shiwaixiangcun.monitor.enums.PriorityLevel;
import com.shiwaixiangcun.monitor.enums.QualityStatus;
import com.shiwaixiangcun.monitor.enums.WorkOrderServiceType;
import com.shiwaixiangcun.monitor.enums.WorkOrderStatus;
import com.shiwaixiangcun.monitor.security.SecurityUtils;
import com.shiwaixiangcun.monitor.service.WorkOrderQualityRecordService;
import com.shiwaixiangcun.monitor.service.WorkOrderService;
import com.shiwaixiangcun.monitor.service.WorkOrderServiceRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/11/23.
 */
@Service
@Transactional
public class WorkOrderQualityRecordServiceImpl extends BaseServiceImpl<WorkOrderQualityRecord, Long> implements WorkOrderQualityRecordService {

    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private WorkOrderServiceRecordService workOrderServiceRecordService;


    @Override
    public Page<WorkOrderQualityRecordDto> recordList(Pageable pageable, MonkeyDto monkeyDto) {
        Searchable searchable = buildSearch(monkeyDto);
        int pageIndex = pageable.getPageNumber() * pageable.getPageSize();
        int pageSize = pageable.getPageSize();
        List<WorkOrderQualityRecord> list = findAll(searchable).getContent();
        List<WorkOrderQualityRecordDto> dtoList = toDto(list);
        if (MonkeyUtils.isNotEmpty(list)) {
            int total = list.size();
            List<WorkOrderQualityRecordDto> limitList = limitList(pageIndex, pageSize, total, dtoList);
            return new PageImpl<WorkOrderQualityRecordDto>(limitList, pageable, total);
        }
        return new PageImpl<WorkOrderQualityRecordDto>(dtoList, pageable, 0);
    }

    @Override
    public void judge(Long qualityRecordId, QualityStatus status, String reason) {
        WorkOrderQualityRecord record = findOne(qualityRecordId);
        if (MonkeyUtils.isEmpty(record)) {
            throw new MonkeyException("该记录不存在");
        }
        if (!QualityStatus.Wait.equals(record.getStatus())) {
            throw new MonkeyException("该工单已质检");
        }

        record.setStatus(status);
        record.setReason(reason);
        save(record);
        WorkOrder workOrder = record.getWorkOrder();
        if (QualityStatus.NoPass.equals(record.getStatus())) {
            workOrder.setStatus(WorkOrderStatus.Accepted);
            workOrderService.save(workOrder);
        }

        String content = "质检了工单,结果为" + status.getLabel() + "。";
        if (MonkeyUtils.isNotEmpty(reason)) {
            content += "理由是：" + reason;
        }
        workOrderServiceRecordService.createServiceRecord(workOrder, WorkOrderServiceType.Quality, content);
    }

    private Searchable buildSearch(MonkeyDto monkeyDto) {
        Searchable searchable = Searchable.newSearchable();
        searchable.addSort(new Sort(Sort.Direction.DESC, "id"));
        searchable.addSearchFilter("user.id", SearchOperator.eq, SecurityUtils.getCurrentUser().getId());

        String level = monkeyDto.getString("level");
        if (MonkeyUtils.isNotEmpty(level)) {
            searchable.addSearchFilter("workOrder.priorityLevel", SearchOperator.eq, PriorityLevel.valueOf(level));
        }
        Long categoryId = monkeyDto.getLong("categoryId");
        if (MonkeyUtils.isNotEmpty(categoryId)) {
            searchable.addSearchFilter("workOrder.category.id", SearchOperator.eq, categoryId);
        }
        String status = monkeyDto.getString("status");
        if (MonkeyUtils.isNotEmpty(status)) {
            searchable.addSearchFilter("status", SearchOperator.eq, QualityStatus.valueOf(status));
        } else {
            searchable.addSearchFilter("status", SearchOperator.ne, QualityStatus.Wait);
        }
        String text = monkeyDto.getString("text");
        if (MonkeyUtils.isNotEmpty(text)) {
            SearchFilter number = SearchFilterHelper.newCondition("workOrder.number", SearchOperator.like, "%" + text + "%");
            SearchFilter title = SearchFilterHelper.newCondition("workOrder.title", SearchOperator.like, "%" + text + "%");
            searchable.or(number, title);
        }
        return searchable;
    }


    public WorkOrderQualityRecord createQualityRecord(WorkOrder workOrder, User user) {
        WorkOrderQualityRecord record = new WorkOrderQualityRecord();
        record.setUser(user);
        record.setStatus(QualityStatus.Wait);
        record.setWorkOrder(workOrder);
        save(record);
        return record;
    }

    @Override
    public WorkOrderDetailDto getDetail(Long id) {
        WorkOrderQualityRecord record = findOne(id);
        WorkOrderDetailDto detail = workOrderService.getDetail(record.getWorkOrder().getId());
        detail.setQualityRecordId(id);
        detail.setQualityStatus(record.getStatus());
        return detail;
    }

    private List<WorkOrderQualityRecordDto> toDto(List<WorkOrderQualityRecord> list) {
        List<WorkOrderQualityRecordDto> dtoList = new ArrayList<>();
        WorkOrderQualityRecordDto dto;
        for (WorkOrderQualityRecord record : list) {
            dto = new WorkOrderQualityRecordDto();
            dto.setId(record.getId());
            dto.setCategoryName(record.getWorkOrder().getCategory().getName());
            dto.setUserName(record.getWorkOrder().getUser().getName());
            dto.setCreateTime(record.getCreateTime());
            dto.setLevel(record.getWorkOrder().getPriorityLevel());
            dto.setNumber(record.getWorkOrder().getNumber());
            dto.setStatus(record.getStatus());
            dto.setTitle(record.getWorkOrder().getTitle());
            dtoList.add(dto);
        }
        return dtoList;
    }

    private <M> List<M> limitList(int pageIndex, int pageSize, int total, List<M> data) {
        // 根据 条件获取到 分页的结构和数据
        List<M> list;
        if (total < pageSize) {
            list = data.subList(pageIndex, total);
        } else {
            int toSize = pageIndex + pageSize;
            if (toSize > total) {
                toSize = pageIndex + total % pageSize;
            }
            list = data.subList(pageIndex, toSize);
        }
        return list;
    }


}
